﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using TraktRater.TraktAPI;
using TraktRater.TraktAPI.DataStructures;
using System.Configuration;

namespace PirateBayDownloader
{
    class Program
    {
        internal class CookieAwareWebClient : WebClient
        {
            private CookieContainer cookie = new CookieContainer();
            public CookieAwareWebClient()
                : base()
            {
                this.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";

            }

            public WebRequest Get(string url)
            {
                return GetWebRequest(new Uri(url));
            }


            protected override WebRequest GetWebRequest(Uri address)
            {
                WebRequest request = base.GetWebRequest(address);
                if (request is HttpWebRequest)
                {
                    (request as HttpWebRequest).CookieContainer = cookie;
                }
                return request;
            }
        }


        static void Main(string[] args)
        {
            var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;

            if (settings["Username"] == null || settings["PiratebayUrl"] == null || settings["PiratebayTopPage"] == null)
            {
                Console.WriteLine("Please all the settings in the .config file !");
                Console.Read();
                return;
            }


            List<TraktMovie> moviesIHave = TraktAPI.GetMovieCollection(settings["Username"].Value);

            CookieAwareWebClient client = new CookieAwareWebClient();
            client.Headers[HttpRequestHeader.UserAgent] = settings["UserAgent"].Value;

            string baseLink = settings["PiratebayUrl"].Value;
            string topPageExtension = settings["PiratebayTopPage"].Value;

            string filename = "Results.html";

            String homeData = client.DownloadString(baseLink);

            String data = client.DownloadString(baseLink + topPageExtension);

            var request = client.Get(baseLink + topPageExtension);

            List<string> links = data.FindAllBetween("<div class=\"detName\">", "</td>\n\t\t<td>\n");

            if (File.Exists(filename)) File.Delete(filename);

            File.AppendAllText(filename, "<html><body>");

            List<string> imdbLinks = new List<string>();

            string[] titleFilters = settings["FilterTitles"].Value.Split(',');

            string[] genreFilters = settings["FilterGenres"].Value.Split(',');

            int rating = int.Parse(settings["MinimumIMDBRating"].Value.Replace(".", "").Replace(",", ""));

            foreach (var link in links)
            {
                try
                {
                    string detailLink = link.FindBetween("<a href=\"/torrent", "\"");
                    detailLink = detailLink.Substring(9, detailLink.Length - 9 - 1);
                    detailLink = baseLink + detailLink;

                    string title = link.FindBetween("title=\"Details for ", "\">");

                    title = title.Substring(18, title.Length - 20);

                  

                   if (!titleFilters.Any(x => title.ToUpper().Contains(x.ToUpper())))
                    {
                        string magnetLink = link.FindBetween("<a href=\"magnet:", "\"");

                        string detailData = client.DownloadString(detailLink);

                        string imdbLink = detailData.FindBetween("http://www.imdb.com/title/", "\"");

                        if (!String.IsNullOrEmpty(imdbLink))
                            imdbLink = imdbLink.Substring(0, imdbLink.Length - 1);

                        if (!imdbLinks.Contains(imdbLink) && !String.IsNullOrEmpty(imdbLink))
                        {
                            imdbLinks.Add(imdbLink);

                            if (!moviesIHave.Any(x => imdbLink.Contains(x.IMDbId) && !String.IsNullOrEmpty(x.IMDbId)))
                            {

                                IMDb.MoviePage page = new IMDb.MoviePage();

                                page.Url = imdbLink;

                                List<TraktMovie> movies = TraktAPI.SearchMovie(page.Name);
                                if (movies == null)
                                {
                                    movies = TraktAPI.SearchMovie(page.Name);

                                }

                                TraktMovie movie = null;
                                if (movies != null)
                                {
                                    movie = movies.Where(x => !String.IsNullOrEmpty(x.IMDbId) && imdbLink.Contains(x.IMDbId)).FirstOrDefault();
                                }
                                if (page.Rating.Contains("."))
                                {
                                    int score = int.Parse(page.Rating.Replace(".", ""));

                                    if (score > rating && ! genreFilters.Any(x => page.Genre.ToUpper().Contains(x.ToUpper())))
                                    {
                                        string output;
                                        if (movie != null)
                                        {
                                            output = magnetLink + "> " + title + " (" + page.Rating + ") " + "</a> - <a href=\"" + imdbLink + "\"> IMDB </a> <a href=\"" + movie.TracktUrl + "\"> Trakt </a> </br>";
                                        }
                                        else
                                        {
                                            output = magnetLink + "> " + title + " (" + page.Rating + ") " + "</a> - <a href=\"" + imdbLink + "\"> IMDB </a> </br>";
                                        }

                                        File.AppendAllText(filename, output);
                                        Console.WriteLine("Added : " + title);

                                    }
                                }
                                else
                                {
                                    Console.WriteLine("Error rating is : " +page.Rating);
                                }
                            }
                            else
                            {
                                TraktMovie movie = moviesIHave.First(x => imdbLink.Contains(x.IMDbId) && !String.IsNullOrEmpty(x.IMDbId));
                                Console.WriteLine("Already have : " + movie.Title);

                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }

            }
            File.AppendAllText(filename, "</body></html>");

            Process.Start(filename);
        }



    }
}
